package com.jiubanqingchen.future.org.interceptor;

import com.jfinal.aop.Aop;
import com.jfinal.aop.Interceptor;
import com.jfinal.aop.Invocation;
import com.jfinal.kit.JsonKit;
import com.jfinal.plugin.activerecord.Record;
import com.jiubanqingchen.future.common.enums.SystemStatus;
import com.jiubanqingchen.future.common.tool.SystemTool;
import com.jiubanqingchen.future.model.models.ExceptionLog;
import com.jiubanqingchen.future.model.models.User;
import com.jiubanqingchen.future.org.admin.BaseController;
import com.jiubanqingchen.future.org.admin.Json;
import com.jiubanqingchen.future.org.business.anonymous.AnonymousService;
import com.jiubanqingchen.future.org.business.log.exceptionLog.ExceptionLogService;
import com.jiubanqingchen.future.org.tool.jwt.JwtService;
import eu.bitwalker.useragentutils.UserAgent;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import javax.servlet.http.HttpServletRequest;

public class OrgInterceptor implements Interceptor {
    private static Logger logger = LoggerFactory.getLogger(OrgInterceptor.class);

    @Override
    public void intercept(Invocation inv) {
        BaseController controller = (BaseController) inv.getController();

        HttpServletRequest request = controller.getRequest();

        String token = request.getHeader("Access-Token");// 得到当前token

        User user = JwtService.verifyToken(token); // 校验token得到用户id

        if (user != null) {
            controller.setSessionAttr("currentUser", user);
        } else {
            //如果当前用户信息为null 判断是否为匿名访问url
            AnonymousService anonymousService = Aop.get(AnonymousService.class);
            boolean flag = anonymousService.judgeIsAnonymous(inv.getActionKey());
            if (!flag) {
                logger.info(SystemStatus.LOGOUT.getCode() + " : " + SystemStatus.LOGOUT.getMsg());
                controller.renderResult(SystemStatus.LOGOUT);
                return;
            }
        }

        try {
            inv.invoke();
        } catch (Exception e) {
            // 捕获全局异常并抛出
            logger.error(e.getMessage());
            controller.renderJson(new Json(SystemStatus.ERROR.getCode(), e.getMessage()));
            new Thread() {
                @Override
                public void run() {
                    createExceptionLog(inv, controller, e); //记录异常信息
                }
            }.start();
        }
    }

    /**
     * 生成异常日志文件
     *
     * @param controller
     * @param e
     */
    private void createExceptionLog(Invocation inv, BaseController controller, Exception e) {
        HttpServletRequest request = controller.getRequest();
        User user = controller.getSessionAttr("currentUser");
        //转成UserAgent对象
        UserAgent userAgent = SystemTool.getUserAgent(request);

        Record ipInfo = SystemTool.getIpInfo(request);

        //获取页面参数
        Record requestRecord = new Record().set("rawData", controller.getRawData()).set("extData", controller.getRecordExtData());

        ExceptionLog exceptionLog = new ExceptionLog();
        exceptionLog.setBrowser(userAgent.getBrowser().getName()).setOs(userAgent.getOperatingSystem().getName()).setLoginIp(ipInfo.getStr("ipAddress"))
                .setLoginUserName(user.getUserName()).setLoginArea(ipInfo.getStr("ipArea")).setExceptionMessage(e.getMessage()).setExceptionData(e.toString())
                .setRequestData(JsonKit.toJson(requestRecord)).setRequestUrl(inv.getActionKey()).setRequestMethod(request.getMethod());
        ExceptionLogService exceptionLogService = Aop.get(ExceptionLogService.class);
        try {
            exceptionLogService.insert(exceptionLog, new Record(), user);
        } catch (Exception exception) {
            logger.error(e.getMessage());
        }
    }

}
